// 导入所需功能组件
import store from '../store/index.js'
import {
	Notification
} from 'element-ui';
import router from '../router/index.js'
import request from './request.js'
((that) => {
	// const userId = store.state.user.userInfo.id
	// const host = process.env.VUE_APP_BASE_API.split('://')[1]
	const host = `${$globalData.host}:9081`
	// const userInfo = store.state.user.userInfo
	// const phone = userInfo.phone
	// const verificationCode = userInfo.verificationCode
	
	// if(userInfo != '' && userInfo != null){
	// 	config.data['phone'] = userInfo.phone
	// 	config.data['verificationCode'] = userInfo.verificationCode
	// 	// config.headers['phone'] = userInfo.phone
	// 	// config.headers['verificationCode'] = userInfo.verificationCode
	// }
	// WebSocket函数注册
	const ws = {
		initMessage: function(userId){
			// 请求是否有离线消息
			request.get('/api/addressBook/MessageController/initMessage', {
				userId,
				// phone,
				// verificationCode
			}).then(res => {
				if (res.code == 200) {
					if (res.data.length > 0) {
						Notification({
							title: '新消息',
							message: `你收到${res.data.length}条新消息，点击前往查看`,
							// type: 'info',
							iconClass: 'el-icon-s-comment',
							onClick() {
								NotificationOnClick()
							},
							duration: 5000
						})
					}
					// console.log("消息初始化成功");
				}
			})
		},
		initWebSocket: function(host = host, userId) {
			// console.log('websock连接'+`ws://${host}/websocket/${userId}`)
			const websock = new WebSocket(`ws://${host}/websocket/${userId}`);
			setTimeout(function(){
				ws.initMessage(userId)
			},300)
			// console.log("WebSocket初始化成功");
			websock.onopen = this.webSocketonOpen;
			websock.onerror = this.webSocketonError;
			websock.onmessage = this.webSocketonMessage;
			websock.onclose = this.webSocketClose;
		},
		webSocketonOpen: function() {
			// console.log("WebSocket连接成功");
			// console.log(ws.initMessage())
		},
		webSocketonError: function(e) {
			throw new Error("WebSocket连接发生错误", e)
		},
		webSocketClose: function(e) {
			// console.log("关闭WebSocket", e);
		},
		webSocketonMessage: function(e) {
			// console.log(e)
			if (router.currentRoute.path !== '/addresslist/interior/message') {
				Notification({
					title: '新消息',
					message: e.data,
					// type: 'info',
					iconClass: 'el-icon-s-comment',
					onClick() {
						NotificationOnClick()
					},
					duration: 5000
				})
			} else {
				store.commit('set_socktNewMessage', e)
			}
			
		}
	}
	// 消息通知点击事件
	function NotificationOnClick() {
		if (router.currentRoute.path !== '/addresslist/interior/message') {
			router.push(`/addresslist/interior/message?t=${new Date().getTime()}`)
			Notification.closeAll()
		} else {
			Notification.closeAll()
		}
	}
	// 全局注册变量
	that.webSocket = ws
})(window)
